<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="合同编号" prop="contractNo">
          <el-input
            v-model="queryParams.contractNo"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in beauty_contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="contractList">
        <el-table-column label="合同编号" align="center" prop="contractNo" width="180" />
        <el-table-column label="订单号" align="center" prop="orderNo" width="180" />
        <el-table-column label="借款金额" align="center" prop="loanAmount" width="120">
          <template #default="scope">
            ¥{{ formatCurrency(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="分期期数" align="center" prop="periods" />
        <el-table-column label="合同状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="beauty_contract_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="签署时间" align="center" prop="signatureTime" width="160" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="success" icon="Download" @click="handleExportPdf(scope.row)">导出PDF</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 合同详情对话框 -->
    <el-dialog title="合同详情" v-model="detailDialog.visible" width="900px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="合同编号">{{ detailDialog.data.contractNo }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ detailDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailDialog.data.userId }}</el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <dict-tag :options="beauty_contract_status" :value="detailDialog.data.status" />
        </el-descriptions-item>
        <el-descriptions-item label="借款金额">¥{{ formatCurrency(detailDialog.data.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="还款总额">¥{{ formatCurrency(detailDialog.data.totalRepayment) }}</el-descriptions-item>
        <el-descriptions-item label="分期期数">{{ detailDialog.data.periods }}期</el-descriptions-item>
        <el-descriptions-item label="月利率">{{ detailDialog.data.interestRate }}%</el-descriptions-item>
        <el-descriptions-item label="签署时间" :span="2">{{ detailDialog.data.signatureTime }}</el-descriptions-item>
        <el-descriptions-item label="合同条款" :span="2">
          <pre style="white-space: pre-wrap; max-height: 300px; overflow-y: auto;">{{ detailDialog.data.contractContent }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="用户签名" :span="2">
          <el-image
            v-if="detailDialog.data.signatureData"
            :src="detailDialog.data.signatureData"
            :preview-src-list="[detailDialog.data.signatureData]"
            style="width: 200px; height: 100px;"
            fit="contain"
          />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleExportPdf(detailDialog.data)">导出PDF</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyContract">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue'
import { listContract, getContract, exportContractPdf, delContract } from '@/api/beauty/contract'
import { ElMessage, ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()
const { beauty_contract_status } = toRefs<any>(proxy.useDict('beauty_contract_status'))

const loading = ref(false)
const total = ref(0)
const contractList = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  contractNo: undefined,
  orderNo: undefined,
  status: undefined
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 查询列表
async function getList() {
  loading.value = true
  const res = await listContract(queryParams)
  contractList.value = res.rows
  total.value = res.total
  loading.value = false
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  proxy.resetForm('queryFormRef')
  handleQuery()
}

// 查看详情
async function handleDetail(row) {
  const res = await getContract(row.contractId)
  detailDialog.data = res.data
  detailDialog.visible = true
}

// 导出PDF
async function handleExportPdf(row) {
  try {
    const res = await exportContractPdf(row.contractId)
    const blob = new Blob([res], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${row.contractNo}.pdf`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该合同吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await delContract(row.contractId)
    ElMessage.success('删除成功')
    getList()
  })
}

// 格式化金额
function formatCurrency(amount) {
  return amount ? Number(amount).toFixed(2) : '0.00'
}

onMounted(() => {
  getList()
})
</script>
